using AutoMapper;
using Microsoft.EntityFrameworkCore;
using ShopForWeb.Models;
using ShopForWeb.Dto.ViewModels;

namespace ShopForWeb.Service;
public class UserService
{
  private ShopDbContext _context;
  private IMapper _mapper;
  public UserService(ShopDbContext context, IMapper mapper)
  {
    _context = context;
    _mapper = mapper;
  }
  public async Task<int> AddUser1Async(UserViewModels uvm)
  {
    var u = _mapper.Map<User>(uvm);
    _context.Entry<User>(u).State = EntityState.Added;
    return await _context.SaveChangesAsync();
  }

  public async Task<List<UserViewModels>> SelectUser1Async()
  {
    var users = await _context.Users.Where(u => u.Sex == "男" && EF.Functions.Like(u.Name, "张%"))
                                    //.AsNoTracking()
                                    .ToListAsync();

    // ViewBag.Users = users;
    return _mapper.Map<List<UserViewModels>>(users);
  }

  public async Task<int> UpdateUser1Async(User u)
  {
    _context.Entry<User>(u).State = EntityState.Modified;
    return await _context.SaveChangesAsync();
  }

  public async Task<UserViewModels?> GetByLoginAsync(string phone, string password)
  {
    var m = await _context.Users.Where(m => m.Phone == phone && m.Password == password)
                             .FirstOrDefaultAsync();
    if (m == null)
      return null;
    return _mapper.Map<UserViewModels>(m);
  }

}
